package com.zzw.service.Impl;

import com.zzw.bean.*;
import com.zzw.bean.SysUser;
import com.zzw.dao.SysUserMapper;
import com.zzw.dao.UserRolesMapper;
import com.zzw.service.SysUserService;
import com.zzw.utils.PasswordEncoderUtil;
import com.zzw.utils.RedisUtil;
import com.zzw.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author 赵志伟
 * @version 1.0
 */
@SuppressWarnings({"all"})
@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private UserRolesMapper userRolesMapper;


    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Override
    public List<SysUser> listByCondition(SysUser sysUser) {
        String username = sysUser.getUsername();
        String mobilePhone = sysUser.getMobilePhone();
        String gender = sysUser.getGender();
        String nickname = sysUser.getNickname();

        SysUserExample sysUserExample = new SysUserExample();
        //通过criteria对象 设置查询条件
        SysUserExample.Criteria criteria = sysUserExample.createCriteria();

        if (StringUtils.hasText(username)) {
            criteria.andUsernameLike("%" + username + "%");
        }
        if (StringUtils.hasText(mobilePhone)) {
            criteria.andMobilePhoneLike("%" + mobilePhone + "%");
        }
        if (StringUtils.hasText(gender)) {
            criteria.andGenderEqualTo(gender);
        }
        if (StringUtils.hasText(nickname)) {
            criteria.andNicknameLike("%" + nickname + "%");
        }
        //如果没有传值, 为 null, "", 或者有空白字符时, 依然是查询所有数据
        sysUserExample.setOrderByClause("create_time desc");
        return sysUserMapper.selectByExample(sysUserExample);
    }

    @Override
    public boolean delete(Integer id) {
        return sysUserMapper.deleteByPrimaryKey(id) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean update(SysUser sysUser) {
        // 如果密码不为空，说明需要更新密码，则进行加密处理
        if (StringUtils.hasText(sysUser.getPassword())) {
            sysUser.setPassword(PasswordEncoderUtil.encode(sysUser.getPassword()));
        }
        
        sysUserMapper.updateByPrimaryKeySelective(sysUser);

        UserRolesExample userRolesExample = new UserRolesExample();
        userRolesExample.createCriteria().andUserIdEqualTo(sysUser.getId());
        userRolesMapper.deleteByExample(userRolesExample);

        Integer userId = sysUser.getId();
        List<String> roles = sysUser.getRoles();

        UserRolesKey userRolesKey = new UserRolesKey();
        userRolesKey.setUserId(userId);

        for (String role : roles) {
            userRolesKey.setRoleId(Integer.valueOf(role));
            userRolesMapper.insertSelective(userRolesKey);
        }

        return true;
    }

    @Override
    public Msg login(SysUser sysUser) {
        log.info("用户登录");
        try {
            if (StringUtils.isEmpty(sysUser.getUsername()) || StringUtils.isEmpty(sysUser.getPassword())) {
                return Msg.fail("用户名和密码不能为空");
            }

            // 根据用户名查询用户
            SysUser user = sysUserMapper.selectByUsername(sysUser.getUsername());
            
            if (user == null) {
                return Msg.fail("用户名或密码错误");
            }
            
            // 使用BCrypt验证密码
            if (!PasswordEncoderUtil.matches(sysUser.getPassword(), user.getPassword())) {
                return Msg.fail("用户名或密码错误");
            }

            HttpSession session = WebUtils.servletRequest.get().getSession();
            session.setAttribute("userId", user.getId());
            session.setAttribute("user", user);

            return Msg.success("登录成功").add("user", user);
        } catch (Exception e) {
            e.printStackTrace();
            return Msg.fail("登录失败：" + e.getMessage());
        }
    }

    @Override
    public SysUser getCurrentUser(Integer userId) {
        return sysUserMapper.selectByPrimaryKey(userId);
    }

    @Override
    public Msg register(SysUser sysUser) {
        if (sysUserMapper.isExistByUsername(sysUser) != null) {
           return Msg.fail("该用户已注册");//说明该用户已注册
        }
        // 对密码进行BCrypt加密
        sysUser.setPassword(PasswordEncoderUtil.encode(sysUser.getPassword()));
        
        int selective = sysUserMapper.insertSelective(sysUser);
        return Msg.success(selective >= 1 ? "注册成功": "注册失败").add("sysUser", sysUser);
    }

    //新增
    @Override
    public Msg add(SysUser sysUser, MultipartFile file) {
        Msg msg = Msg.success();

        if (sysUserMapper.isExistByUsername(sysUser) != null) {
            //说明该用户已注册
            msg.setMsg("该用户已存在");
        } else {
            // 对密码进行BCrypt加密
            sysUser.setPassword(PasswordEncoderUtil.encode(sysUser.getPassword()));
            
            int selective = sysUserMapper.insertSelective(sysUser);
            msg.add("sysUser", sysUser) .setMsg(selective >= 1 ? "新增成功": "新增失败");
        }

        return msg;
    }

    @Override
    public boolean updateAvatar(Integer userId, String avatarUrl) {
        SysUser sysUser = new SysUser();
        sysUser.setId(userId);
        sysUser.setAvatar(avatarUrl);
        return sysUserMapper.updateByPrimaryKeySelective(sysUser) > 0;
    }

    @Override
    public boolean updateUserInfo(SysUser sysUser) {
        // 只更新允许用户修改的字段
        SysUser updateUser = new SysUser();
        updateUser.setId(sysUser.getId());
        updateUser.setNickname(sysUser.getNickname());
        updateUser.setEmail(sysUser.getEmail());
        updateUser.setMobilePhone(sysUser.getMobilePhone());
        updateUser.setGender(sysUser.getGender());

        // 更新用户信息
        int result = sysUserMapper.updateByPrimaryKeySelective(updateUser);

        // 更新session中的用户信息
        if (result > 0) {
            HttpSession session = WebUtils.servletRequest.get().getSession();
            SysUser currentUser = (SysUser) session.getAttribute("user");
            if (currentUser != null && currentUser.getId().equals(sysUser.getId())) {
                currentUser.setNickname(sysUser.getNickname());
                currentUser.setEmail(sysUser.getEmail());
                currentUser.setMobilePhone(sysUser.getMobilePhone());
                currentUser.setGender(sysUser.getGender());
                session.setAttribute("user", currentUser);
            }
        }

        return result > 0;
    }

    @Override
    public boolean changePassword(Integer userId, String oldPassword, String newPassword) {
        // 1. 根据用户ID查询用户
        SysUser user = sysUserMapper.selectByPrimaryKey(userId);
        if (user == null) {
            return false;
        }

        // 2. 验证旧密码是否正确（使用BCrypt比较）
        if (!PasswordEncoderUtil.matches(oldPassword, user.getPassword())) {
            return false;
        }

        // 3. 更新新密码（使用BCrypt加密）
        SysUser updateUser = new SysUser();
        updateUser.setId(userId);
        updateUser.setPassword(PasswordEncoderUtil.encode(newPassword));

        return sysUserMapper.updateByPrimaryKeySelective(updateUser) > 0;
    }

    /**
     * 根据用户名查找用户
     * @param username 用户名
     * @return 用户对象
     */
    @Override
    public SysUser findByUsername(String username) {
        // 调用Mapper中的方法查询用户
        return sysUserMapper.selectByUsername(username);
    }

    /**
     * 获取用户的权限列表
     * @param userId 用户ID
     * @return 权限标识列表
     */
    @Override
    public List<String> getUserPermissions(Integer userId) {
        // 查询用户的所有权限
        return sysUserMapper.selectPermissionsByUserId(userId);
    }

    /**
     * 发送手机验证码
     * @Param mobilePhone 手机号码
     * @return 验证码
     */
    public String sendSms(String mobilePhone) {
        //手机号校验
        if (StringUtils.isEmpty(mobilePhone)) {
            return "手机号不能为空";
        }
        return "";
    }

}
